#include "save_task.h"
#include "codec_task.h"
#include "ff.h"
#include "common_utils.h"
#include "lwrb/lwrb.h"


char* filename="0:/audio.bin";

static uint32_t g_AudioOffset=0;
static uint8_t g_audioBuf[1024]= {0};


/**
 * 函数功能：存储任务初始化
 */
void save_task_init(void)
{
    FRESULT frResult;
    FIL fp;
    frResult = f_open(&fp, filename, FA_OPEN_ALWAYS | FA_READ | FA_WRITE);

    if (frResult != FR_OK)
    {
        APP_PRINT("file create err\r\n");
    }
}

/**
 * 函数功能：存储任务
 */
void save_task(void)
{
    FRESULT frResult;
    FIL fp;
    uint32_t cbsize=0;
    uint32_t cbretsize = 0;
    lwrb_sz_t buf_size=0;

    buf_size=lwrb_get_full(&g_lwrb_enc);

    if(buf_size>=1024)
    {
        buf_size=lwrb_get_full(&g_lwrb_enc);

        frResult = f_open(&fp, filename, FA_WRITE);

        if (frResult == FR_OK)
        {
            frResult = f_lseek(&fp, g_AudioOffset);

            if (frResult == FR_OK)
            {
                cbsize=lwrb_read(&g_lwrb_enc,g_audioBuf,1024);
                frResult = f_write(&fp, g_audioBuf, cbsize, &cbretsize);

                if (frResult == FR_OK)
                {
                    g_AudioOffset+=cbsize;
                }
            }
        }
    }
}